﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ServiceKit.JsonRpc
{
    public class RpcParametersJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return true;
        }
        
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, value);
        }

        //重写ReadJson方法
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            switch (reader.TokenType)
            {
                case JsonToken.StartObject: //对象
                    try
                    {
                        JObject jObject = JObject.Load(reader);
                        return jObject.ToObject<Dictionary<string, object>>();
                    }
                    catch (Exception)
                    {
                        throw new Exception("params参数只能是Object[]数组、Json对象或null。");
                    }
                case JsonToken.StartArray: //数组
                    return JArray.Load(reader).ToObject<object[]>(serializer);
                case JsonToken.Null: //为空，未定义
                    return null;
            }
            throw new Exception("params参数只能是Object[]数组、Json对象或null。");
        }
    }
}
